//
//  Kylin_TabBar.m
//  03-BuDeJie-2 TabBar设置
//
//  Created by Kylin on 16/2/3.
//  Copyright © 2016年 kylin. All rights reserved.
//

#import "Kylin_TabBar.h"
#import "Kylin_PublishViewController.h"
@interface Kylin_TabBar()

/**publish Button*/
@property(nonatomic,weak)UIButton *publishButton;

/**privousButtonTag */
@property(nonatomic,assign)NSInteger privousClickButtonTag;
@end

@implementation Kylin_TabBar


#pragma mark- 自定义TarBar
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        UIButton *publishButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [publishButton setBackgroundImage:[UIImage imageNamed:@"tabBar_publish_icon"] forState:UIControlStateNormal];
        
        [publishButton setBackgroundImage:[UIImage imageNamed:@"tabBar_publish_click_icon"] forState:UIControlStateHighlighted];
        
        [publishButton sizeToFit]; // 自动适应
        
        [publishButton addTarget:self action:@selector(publishButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:publishButton];
        
        self.publishButton = publishButton;
        
    }
    return self;
}


#pragma mark- 发布按钮点击
- (void)publishButtonClick{
    
    Kylin_PublishViewController *publish = [[Kylin_PublishViewController alloc]init];
    
    // 使用系统窗口的VIEW来推送MODAL
    [self.window.rootViewController presentViewController:publish animated:NO completion:nil];
}
#pragma mark- 自定义布局所有子控件
- (void)layoutSubviews{
    
    [super layoutSubviews];
    
    self.publishButton.center = CGPointMake(self.frame.size.width * 0.5, self.frame.size.height * 0.5);
    
    // 按钮索引
    NSInteger index = 0;
    
    //按钮尺寸
    CGFloat tabBarButtonW = self.frame.size.width / 5;
    CGFloat tabBarButtonH = self.frame.size.height;
    CGFloat tabBarButtonY = 0;
    
    for (UIControl  *tabBarButton in self.subviews) {
        
        // 如果不不是UITabBarButton 那就不执行下面代码
        if (![NSStringFromClass(tabBarButton.class) isEqualToString:@"UITabBarButton"]) continue;
       
        // 计算按钮的X值
        CGFloat tabBarButtonX = index * tabBarButtonW;
        
        // 如果是第二个
        if (index >= 2) {
            tabBarButtonX += tabBarButtonW;
        }
        
        tabBarButton.frame = CGRectMake(tabBarButtonX, tabBarButtonY, tabBarButtonW, tabBarButtonH);
        
        // 索引加1
        index ++;
        
        // 监听tabBarButton点击
        [tabBarButton addTarget:self action:@selector(tabBarButtonDidRepeatClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    
}

- (void)tabBarButtonDidRepeatClick:(UIControl *)tabBarButton{
    
    if (self.privousClickButtonTag == tabBarButton.tag) {
        
        [[NSNotificationCenter defaultCenter]postNotificationName:Kylin_tabBarButtonDidRepeatClickNotification object:nil];
    }
    
    self.privousClickButtonTag = tabBarButton.tag;
}
@end
